from concurrent.futures import ThreadPoolExecutor
import threading
from time import sleep
from rpc.pubsub_pb2_grpc import add_pubsubServicer_to_server, pubsubServicer
from rpc.pubsub_pb2 import mes2client, mes2server
import grpc

class MyServicer(pubsubServicer):

    def __init__(self) -> None:
        super().__init__()
        self.threadLock = threading.Lock()
        self.n = 0
        self.mes = "1145141919810"
        self.lifetime = 20
        

    def pubsubServer(self, request, context):
        
        
        if self.n == 0:
            self.threadLock.acquire()  
            self.n += 1
            sleep(1)
            self.lifetime -= 1
            self.threadLock.release()  
        self.threadLock.acquire()  
        self.n = 0
        self.threadLock.release()  

        alive = 0
        if self.lifetime > 0:
            alive = 1

        return mes2client(timelabel = alive,mes2 = self.mes)

def serverfunc():
    server = grpc.server(ThreadPoolExecutor(max_workers=3))
    add_pubsubServicer_to_server(MyServicer(), server)

    server.add_insecure_port('[::]:50000')
    server.start()
    server.wait_for_termination()

if __name__ == '__main__':
    serverfunc()
